package com.zjh.controller.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import com.zjh.pojo.Role;
import com.zjh.pojo.User;
import com.zjh.service.role.RoleService;
import com.zjh.service.user.UserService;
import com.zjh.util.Constants;
import com.zjh.util.PageSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    @Qualifier("UserServiceImpl")
    UserService userService;

    @Autowired
    @Qualifier("RoleServiceImpl")
    RoleService roleService;

    @PostMapping("/login.do")
    public String login(String userCode, String userPassword, Model model, HttpServletRequest req, RedirectAttributes attributes) {
        User loginUser = userService.getLoginUser(userCode);
        if (loginUser != null) {
            if (userPassword.equals(loginUser.getUserPassword())) {
                req.getSession().setAttribute(Constants.USER_SESSION, loginUser);
                return "frame";
            } else {
                attributes.addAttribute("error", "用户名或密码不正确");
                return "redirect:login.jsp";
            }
        } else {
            attributes.addAttribute("error", "用户名或密码不正确");
            return "redirect:login.jsp";
        }
    }

    @RequestMapping("/toUpdatePwd")
    public String toUpdatePwd() {
        return "pwdmodify";
    }

    @GetMapping("/user.do")
    @ResponseBody
    public String checkPwd(HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");
        Map<String, String> resultMap = new HashMap<String, String>();
        if (user == null) {
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) {
            resultMap.put("result", "false");
        } else {
            String userPassword = user.getUserPassword();
            if (oldpassword.equals(userPassword)) {
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }

    @PostMapping("/user.do")
    public String updatePwd(HttpServletRequest req, String oldpassword, String newpassword, Model model, RedirectAttributes attributes) {
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        if (user.getUserPassword().equals(oldpassword) && !StringUtils.isEmptyOrWhitespaceOnly(newpassword)) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("userPassword", newpassword);
            int i = userService.updatePwd(map);
            if (i > 0) {
                model.addAttribute("error", "修改密码成功，请退出后重新登录");
                req.getSession().removeAttribute(Constants.USER_SESSION);
                return "redirect:login.jsp";
            } else {
                attributes.addAttribute(Constants.SYS_MESSAGE, "密码修改失败");
                return "pwdmodify";
            }
        } else {
            attributes.addAttribute(Constants.SYS_MESSAGE, "输入有误");
            return "pwdmodify";
        }
    }

    @RequestMapping("/queryUser")
    public String query(String queryname, String queryUserRole, String pageIndex, HttpServletRequest req) {
        int userRole = 0;
        //设置每页显示的页面容量
        int pageSize = Constants.pageSize;
        //设置当前的默认页码
        int currentPageNo = 1;

        //这里为空，会查询所有记录
        if (queryname == null) {
            queryname = "";
        }
        if (queryUserRole != null && !queryUserRole.equals("")) {
            userRole = Integer.parseInt(queryUserRole);
        }
        //说明当前用户有进行设置跳转页面
        if (pageIndex != null) {
            currentPageNo = Integer.parseInt(pageIndex);
        }

        Map<String, Object> mapCount = new HashMap<>();
        mapCount.put("userName", queryname);
        mapCount.put("userRole", userRole);

        int totalCount = userService.getUserCount(mapCount);

        PageSupport pageSupport = new PageSupport();
        //根据总记录条数以及当前每页的页面容量可以算出，一共有几页，以及最后一页的显示条数
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        //可显示总页数
        int totalPageCount = pageSupport.getTotalPageCount();

        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        //重要
        int currentIndex = (currentPageNo - 1) * pageSize;

        Map<String, Object> userMap = new HashMap<>();
        userMap.put("userName", queryname);
        userMap.put("userRole", userRole);
        userMap.put("indexPage", currentIndex);
        userMap.put("pageSize", pageSize);
        List<User> userList = userService.getUserList(userMap);

        List<Role> roleList = roleService.getRoleList();

        //得到了用户表与角色表以及各种经过处理后的参数，都存进req中
        req.setAttribute("userList", userList);
        req.setAttribute("roleList", roleList);
        req.setAttribute("queryUserName", queryname);
        req.setAttribute("queryUserRole", userRole);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);

        return "userlist";
    }

    @RequestMapping("/ucExist")
    @ResponseBody
    public String ucExist(String userCode) {
        User loginUser = userService.getLoginUser(userCode);
        Map<String, String> map = new HashMap<>();

        if (StringUtils.isNullOrEmpty(userCode)) {
            map.put("userCode", "exist");
        } else {
            if (loginUser != null) {
                map.put("userCode", "exist");
            } else {
                map.put("userCode", "notexist");
            }
        }

        return JSONArray.toJSONString(map);
    }


    @RequestMapping("/getRoleList")
    @ResponseBody
    public String getRoleList() {
        List<Role> roleList = roleService.getRoleList();
        System.out.println(roleList);

        return JSONArray.toJSONString(roleList);
    }

    @RequestMapping("/delUser")
    @ResponseBody
    public String delUser(int id) {
        Map<String, String> map = new HashMap<>();
        if (id <= 0) {
            map.put("delResult", "notexist");
        } else {
            int i = userService.deleteUserById(id);
            if (i > 0) {
                map.put("delResult", "true");
            } else {
                map.put("delResult", "false");
            }
        }
        return JSONArray.toJSONString(map);
    }

    @RequestMapping("/addUser")
    public String addUser(HttpServletRequest req) throws ParseException {
        Map<String, Object> map = new HashMap<>();

        map.put("userCode", req.getParameter("userCode"));
        map.put("userName", req.getParameter("userName"));
        map.put("userPassword", req.getParameter("userPassword"));
        map.put("gender", req.getParameter("gender"));
        Date birthday = new SimpleDateFormat("yyyy-MM-dd").parse(req.getParameter("birthday"));
        map.put("birthday", birthday);
        map.put("phone", req.getParameter("phone"));
        map.put("address", req.getParameter("address"));
        map.put("userRole", req.getParameter("userRole"));
        map.put("createdBy", ((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        int add = userService.add(map);

        if (add > 0) {
            return "redirect:/queryUser";
        } else {
            return "useradd";
        }

    }

    @RequestMapping("/toAddUser")
    public String toAddUser() {
        return "useradd";
    }

    @GetMapping("/view")
    public String view(HttpServletRequest req, int id) {
        if (id > 0) {
            User user = userService.getUserById(id);
            req.setAttribute("user", user);
        }
        return "userview";
    }

    @RequestMapping("/toModify")
    public String toModify(HttpServletRequest req, int id) {
        if (id > 0) {
            User user = userService.getUserById(id);
            req.setAttribute("user", user);
        }
        return "usermodify";
    }

    @RequestMapping("/modify")
    public String modify(HttpServletRequest req) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        String id = req.getParameter("id");

        String userName = req.getParameter("userName");
        int gender = Integer.parseInt(req.getParameter("gender"));
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        int userRole = Integer.parseInt(req.getParameter("userRole"));

        map.put("id", id);
        map.put("userName", userName);
        map.put("gender", gender);
        map.put("birthday", new SimpleDateFormat("yyyy-MM-dd").format(new Date(birthday)));
        map.put("phone", phone);
        map.put("address", address);
        map.put("userRole", userRole);
        map.put("modifyBy", ((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        int modify = userService.modify(map);

        return "redirect:/queryUser";

    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest req) {
        req.getSession().removeAttribute(Constants.USER_SESSION);
        return "redirect:/";
    }

}
